import sys
import os
import ast
import subprocess
import io
import os.path

# sys.executable

# 设置输出为中文编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', line_buffering=True)
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', line_buffering=True)
# 获取当前目录，仅限打包后
if getattr(sys, 'frozen', False):
    base_dir = os.path.dirname(sys.executable)
else:
    base_dir = os.path.join(os.path.dirname(__file__),'dist')

def checkin():
    arguments = {}
    try:
        # 取出参数
        for i in range(len(sys.argv)):
            if sys.argv[i] == "--help":
                print("""
                --help: 显示帮助信息
                --version: 显示版本信息
                --count: 设置输出算式数量
                --col: 设置输出列数
                --level: 设置运算级别
                --title: 添加标题
                """)
                sys.exit()
            elif sys.argv[i] == "--version":
                print("version: 1.0.0")
                sys.exit()
            elif sys.argv[i] == "--level":
                arguments["level"] = sys.argv[i+1]
            elif sys.argv[i] == "--count":
                arguments["count"] = sys.argv[i+1]
            elif sys.argv[i] == "--col":
                arguments["col"] = sys.argv[i+1]
            elif sys.argv[i] == "--title":
                arguments["title"] = sys.argv[i+1]
    except Exception as e:
        return {"status": False, "data": str(e)}

    # 检查需要的参数是否都在里面
    for i in ['count', 'col','level']:
        if 'title' not in arguments.keys():
            arguments["title"] = "title"
            continue
        if i not in arguments.keys():
            return {"status": False, "data": f"缺少参数{i}"}
    
    # 尝试转换参数
    try:
        arguments["col"] = int(arguments["col"])
    except Exception as e:
        return {"status": False, "data": str(e)}
    
    # 如果一切无误，则返回参数
    return {"status": True, "data": arguments}

"""把任意可迭代对象按宽度 n 切片，返回列表套列表。"""
def chunk(seq, n: int):
    return [seq[i:i+n] for i in range(0, len(seq), n)]

def main(data):
    computed = []
    # 获取调用程序的路径
    cwd = os.path.join(base_dir,'core','computed_base.exe')
    cmd = [cwd, '--count', data['count'] ,'--level', data['level']]      # 换成你要执行的命令/参数列表
    proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,           # 如果想把 stderr 也一起捕获
            bufsize=1,                          # 1=行缓冲
            universal_newlines=True)            # 文本模式，等价于 text=True（Py≥3.7）

    # 逐行读取
    try:
        for line in proc.stdout:
            # print('>>>', line, end='')             # 这里已经带 \n，所以 end=''
            _c = ast.literal_eval(line)
            computed.append(f"{_c['arg1']}{_c['symbol']}{_c['arg2']}=")
    except Exception as e:
        print(e)
        sys.exit()
    proc.wait()
    format_out = chunk(computed, data['col']) # 先打印标题
    print(f"{data['title']}{"".join([","]*(data['col']-1))}")
    for i in format_out:
        print(",".join(i))

if '__main__' == __name__:
    data = checkin()
    if data["status"]:
        main(data=data["data"])
    else:
        print(data["data"])
    